package com.woniuxy.shirocore;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName MyRealmDemo
 * @Description TODO
 * @Author LI.hh
 * @Date 2022/9/5 16:26
 * @Version 1.0
 */
public class MyRealmDemo extends AuthorizingRealm {
    private final String REALMNAME="MyRealm";
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if(principalCollection.getRealmNames().contains(REALMNAME)){
            String username = principalCollection.getPrimaryPrincipal()+"";
            //模拟数据库去角色表和权限表中查询数据出来，并封装到AuthorizationInfo里面
            Set<String> roles = new HashSet<>();//封装角色，数据库查出来封装到set就会去重
            roles.add("admin");
            roles.add("manager");
            Set<String> perms = new HashSet<>();//封装权限
            perms.add("manager:addOne");
            perms.add("manager:edit");
            perms.add("manager:delete");
            perms.add("manager:findOne");
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.setRoles(roles);
            simpleAuthorizationInfo.setStringPermissions(perms);
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if(token instanceof UsernamePasswordToken){
            UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
            String username= usernamePasswordToken.getUsername();
            //真实开发从数据库查询
            String password = "123456";
            if(password.equals(new String(usernamePasswordToken.getPassword()))){
                System.out.println("登录成功");
                return new SimpleAuthenticationInfo(username,password,REALMNAME);
            }
        }
        return null;
    }
}
